<template>
	<view class="container">
		<!-- 评价有礼 -->
		<view class="header">
			<text class="header-title">评价有礼</text>
			<br>
			<text class="header-description">感谢您购买我们家商品。</text>
		</view>

		<!-- 表单区域 -->
		<view class="form">
			<!-- 手机号码 -->
			<view class="form-item">
				<text class="form-label">手机号码 <text class="hint" @tap="showExample('phone')">(点击查看示例)</text></text>
				<view class="form-content">
					<input class="form-input" placeholder="请填写手机号码" v-model="phone" type="number" maxlength="11" />
				</view>
			</view>

			<!-- 评价平台 -->
			<view class="form-item">
				<text class="form-label">评价平台</text>
				<view class="form-content">
					<picker :range="platforms" :value="selectedPlatformIndex" @change="onPlatformChange">
						<view class="picker">
							{{ platforms[selectedPlatformIndex] || '请选择' }}
						</view>
					</picker>
				</view>
			</view>

			<!-- 自定义平台名称 -->
			<view v-if="isCustomPlatform" class="form-item">
				<text class="form-label">自定义平台名称</text>
				<view class="form-content">
					<input class="form-input" placeholder="请输入自定义平台名称" v-model="customPlatformName" />
				</view>
			</view>

			<!-- 订单编号 -->
			<view class="form-item">
				<text class="form-label">订单编号 <text class="hint" @tap="showExample('order')">(点击查看示例)</text></text>
				<view class="form-content">
					<input class="form-input" placeholder="请填写下单平台订单编号" v-model="orderNumber" />
				</view>
			</view>

			<!-- 上传评价截图 -->
			<view class="form-item">
				<text class="form-label">上传评价截图</text>
				<view class="form-content">
					<view class="upload-list">
						<view v-for="(image, index) in uploadedFiles" :key="index" class="upload-item">
							<image class="uploaded-image" :src="image.preview" />
						</view>
						<view class="upload-item" @tap="chooseImages">
							<text class="upload-placeholder">+</text>
							<text class="upload-text">点击上传</text>
						</view>
					</view>
				</view>
			</view>
			<up-button class="submit-button" text="去首页" @click="navigateToUserIndex()"></up-button>
		</view>
		<view>
			<button class="submit-button" @tap="submitEvaluation" :disabled="!isFormValid">
				确认提交
			</button>
		</view>

		<!-- 示例弹窗 -->
		<view v-if="showModal" class="popup">
			<view class="popup-container">
				<text class="popup-title">手机号就是您下单时的手机号，11位手机号，订单号就是订单详情页，如图的订单编号</text>
				<image class="popup-image" src="/static/image/submit_evaluation/订单编号.jpg" />
				<button class="popup-close" @tap="closeModal">关闭</button>
			</view>
		</view>
		<up-popup :show="show" :round="10" mode="center" @close="close" :safeAreaInsetBottom="false">
			<view>
				<view class="grid-container">
					<template v-for="(item, index) in awards" :key="item.id">
						<view class="grid-item" :class="{'active':activeIndex === index }" v-if="index != 4">
							<image :src="item.image" mode="aspectFit"></image>
							<text>{{ item.name }}</text>
						</view>
						<view class="grid-item" v-else @click="startLottery()">
							<image :src="item.image" mode="aspectFit"></image>
							<text>{{ item.name }}</text>
						</view>
					</template>
				</view>
				<view class="txt">
					<text>剩余{{prizeNumber}}次</text>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		addEvaluationRecordsSubmittedByUser,
		userLogin
	} from "@/common/api.js"; // 引入 API

	// 页面跳转函数
	const navigateToUserIndex = () => {
		// 使用微信小程序的导航接口跳转
		uni.navigateTo({
			url: '/pages/user_index/user_index'
		});
	};
	// 表单数据
	const phone = ref('');
	const orderNumber = ref('');
	const platforms = ['饿了么', '美团', '自定义平台'];
	const selectedPlatformIndex = ref(null);
	const customPlatformName = ref('');
	const uploadedFiles = ref([]);
	const showModal = ref(false);

	// 计算属性
	const isCustomPlatform = computed(() => platforms[selectedPlatformIndex.value] === '自定义平台');
	const isFormValid = computed(() =>
		phone.value &&
		orderNumber.value &&
		selectedPlatformIndex.value !== null &&
		uploadedFiles.value.length > 0 &&
		(!isCustomPlatform.value || customPlatformName.value)
	);

	onMounted(() => {
		// 接收其他页面跳转到当前页面传入的参数
		const params = getCurrentPages().pop().options?.orderNumber;
		// const params = getCurrentPages()[getCurrentPages().length - 1].options;
		if (params) {
			orderNumber.value = params;
		}

		// 请求微信获取loginCode
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				if (loginRes.code) {
					userLogin(loginRes.code).then((res) => {
						console.log(res);
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('userId', res.data.userId);
					}).catch((err) => {
						console.log(err);
					})
				}
			},
			fail: () => {
				uni.showToast({
					title: '微信登录失败，请重试',
					icon: 'error',
				})
			}
		})
	})

	// 图片选择后转换为 Base64 并保存
	const chooseImages = () => {
		uni.chooseImage({
			count: 5,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				for (const filePath of res.tempFilePaths) {
					try {
						const base64 = await convertToBase64(filePath);
						uploadedFiles.value.push({
							preview: base64, // 用于页面展示
							filePath: base64, // 保存 Base64 格式的文件数据
						});
						uni.showToast({
							title: '图片处理成功',
							icon: 'success'
						});
					} catch (err) {
						console.error('图片处理失败', err);
						uni.showToast({
							title: '图片处理失败',
							icon: 'none'
						});
					}
				}
			},
			fail: () => uni.showToast({
				title: '选择图片失败',
				icon: 'none'
			}),
		});
	};

	// 将图片文件转换为 Base64 格式
	const convertToBase64 = (filePath) => {
		return new Promise((resolve, reject) => {
			uni.getFileSystemManager().readFile({
				filePath,
				encoding: 'base64',
				success: (res) => resolve(`data:image/jpeg;base64,${res.data}`),
				fail: (err) => reject(err),
			});
		});
	};

	// 提交评价数据
	const submitEvaluation = async () => {
		if (!isFormValid.value) {
			uni.showToast({
				title: '请填写完整表单信息',
				icon: 'none'
			});
			return;
		}

		const formData = {
			phone: phone.value,
			orderNumber: orderNumber.value,
			submitPlatform: isCustomPlatform.value ?
				customPlatformName.value : platforms[selectedPlatformIndex.value],
			imagesWithBase64: uploadedFiles.value.map(file => file.filePath),
			shopId: '3',
		};
		addEvaluationRecordsSubmittedByUser(formData).then((res) => {
			if (res.code === 200) {
				// 保存token
				uni.showToast({
					title: `${res.msg}`,
					icon: 'success'
				});
				show.value = true;
			}
		}).catch((err) => {
			console.log(err);
		})



	};

	// 平台选择变更
	const onPlatformChange = (e) => {
		selectedPlatformIndex.value = e.detail.value;
		if (!isCustomPlatform.value) customPlatformName.value = '';
	};

	// 显示和关闭示例弹窗
	const showExample = () => showModal.value = true;
	const closeModal = () => showModal.value = false;


	const awards = ref([{
			id: 1,
			name: '最低红包',

			image: 'https://bj.bcebos.com/bjh-pixel/17105473710333046746_0_ainote_new.jpg'
		},
		{
			id: 2,
			name: '随机红包',
			image: 'https://img2.baidu.com/it/u=1490310887,277713106&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400'
		},
		{
			id: 3,
			name: '最高红包',
			image: 'https://bj.bcebos.com/bjh-pixel/17105473710333046746_0_ainote_new.jpg'
		},
		{
			id: 4,
			name: '免单',
			image: 'https://img2.baidu.com/it/u=1490310887,277713106&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400'
		},
		{
			id: 5,
			name: '点击抽奖',
			image: 'https://pic.ibaotu.com/02/23/27/229888piCvVa.jpg!w280'
		},
		{
			id: 6,
			name: '神秘奖励',
			image: 'https://img2.baidu.com/it/u=1490310887,277713106&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400'
		},
		{
			id: 7,
			name: '外卖会员',
			image: 'https://bj.bcebos.com/bjh-pixel/17105473710333046746_0_ainote_new.jpg'
		},
		{
			id: 8,
			name: '88元',
			image: 'https://img2.baidu.com/it/u=1490310887,277713106&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400'
		},
		{
			id: 9,
			name: '外卖劵',
			image: 'https://bj.bcebos.com/bjh-pixel/17105473710333046746_0_ainote_new.jpg'
		}
	]);
	const show = ref(false);

	// 关闭抽奖
	const close = () => {
		show.value = false;
		// 跳转到首页
		navigateToUserIndex();
	};
	// 当前激活的奖品索引
	const activeIndex = ref(-1);
	// 抽奖是否在进行中
	const isLotteryRunning = ref(false);
	// 抽奖的定时器
	let lotteryInterval = null;
	// 最终停止的奖品索引
	const finalIndex = ref(-1);
	const prizeNumber = ref(1); // 假设抽奖次数为 1
	const startLottery = () => {
		// 如果抽奖次数为 0，直接返回并提示
		if (prizeNumber.value === 0) {
			uni.showToast({
				title: '抽奖次数已用完，欢迎下次再来！',
				icon: 'none',
			});
			return;
		}

		// 如果抽奖已经在进行中，则不再重复触发
		if (isLotteryRunning.value) return;

		isLotteryRunning.value = true;

		// 固定随机到的索引（例如固定到索引 2）
		const fixedIndex = 1; // 这里可以改为你希望固定的索引值
		finalIndex.value = fixedIndex; // 设置最终停止的索引为固定值

		lotteryInterval = setInterval(() => {
			activeIndex.value = (activeIndex.value + 1) % awards.value.length; // 循环切换激活的奖品
		}, 100); // 每100毫秒切换一次

		// 模拟抽奖过程，3秒后停止
		setTimeout(() => {
			clearInterval(lotteryInterval);
			activeIndex.value = finalIndex.value; // 停止到固定索引
			isLotteryRunning.value = false;

			// 根据剩余次数提示
			if (prizeNumber.value >= 0) {
				uni.showToast({
					title: '恭喜你，中奖啦！金额将在商家审核后发出',
					icon: 'none',
				});

				// 延时跳转
				setTimeout(() => {
					uni.showToast({
						title: '正在跳转首页',
						icon: 'none',
					});
					navigateToUserIndex();
				}, 2000)

			} else {
				uni.showToast({
					title: '抽奖次数已用完，欢迎下次再来！',
					icon: 'none',
				});

			}

			// 减少抽奖次数
			prizeNumber.value--;
		}, 3000);

	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		height: calc(100vh - 20rpx);
	}

	.header {

		padding: 20rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.header-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.header-description {
		font-size: 28rpx;
		color: #666;
	}

	.form {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.hint {
		font-size: 24rpx;
		color: #f62c33;
		cursor: pointer;
	}

	.form-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border: 1rpx solid #ddd;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		// background-color: #f9f9f9;
	}

	.picker {
		font-size: 24rpx;
		color: #999;
	}

	.arrow {
		width: 20rpx;
		height: 20rpx;
	}

	.upload-section {
		margin-bottom: 20rpx;
	}

	.upload-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.upload-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.upload-item {
		width: 160rpx;
		height: 160rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		// background-color: #eee;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.upload-placeholder {
		font-size: 72rpx;
		color: #aaa;
	}

	.upload-text {
		font-size: 24rpx;
		color: #aaa;
		margin-top: 10rpx;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.submit-button {
		width: 60%;
		padding: 30rpx;
		font-size: 32rpx;
		color: #fff;
		background-color: #f62c33;
		border-radius: 10rpx;
		text-align: center;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.submit-button:disabled {
		background-color: #ccc;
	}

	.popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.popup-container {
		width: 90%;
		max-width: 800rpx;
		background: white;
		border-radius: 16rpx;
		overflow: hidden;
		text-align: center;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.popup-image {
		width: 600rpx;
		height: 400rpx;
		object-fit: cover;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.popup-close {
		font-size: 28rpx;
		color: white;
		background-color: #f62c33;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
		border: none;
		cursor: pointer;
	}

	.form-input {
		width: 100%;
	}


	.grid-container {
		display: grid;
		background: #c95c5c;
		grid-template-columns: repeat(3, 1fr);
		grid-template-rows: repeat(3, 1fr);
		gap: 20rpx;
		width: 452rpx;
		height: 500rpx;
		width: 500rpx;
		border-radius: 10rpx 10rpx 0 0;
		/* 上面两个圆角，下面不变 */
		padding: 10px;
	}

	.grid-item {
		background-color: white;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		border-radius: 20rpx;
	}

	.grid-item.active {
		border: 6rpx solid limegreen;
	}

	.grid-item image {
		width: 80rpx;
		height: 80rpx;
	}

	.txt {
		width: 100%;
		margin: 20rpx auto;
		display: flex;
		justify-content: center;
	}
</style>